/**
 * App router config
 */
import Vue from 'vue'
import VueRouter from 'vue-router'
import otherModuleRoutes from './module'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/token'
import store from '@/store'
Vue.use(VueRouter)

NProgress.configure({showSpinner: false})

const routes = [{
  path: '/login',
  component: (resolve) => {
    import('@/views/login/index.vue').then(resolve)
  },
  meta: {
    skipAuth: true
  }
}, {
  path: '/',
  component: (resolve) => {
    import('@/views/layout/Layout.vue').then(resolve)
  },
  children: [...otherModuleRoutes, {
    path: '/', redirect: '/dashboard'
  }]
}, {
  path: '*',
  component: {
    render (h) {
      return h('div', {staticClass: 'flex flex-main-center', attrs: { style: 'width:100%;font-size:32px' }}, 'Page not found')
    }
  }
}]

const router = new VueRouter({
  mode: 'history',
  linkActiveClass: 'active',
  scrollBehavior: () => ({ y: 0 }),
  routes
})

// router
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    if (!store.getters.id) {
      // 初始化用户信息
      store.dispatch('userInfo')
    }
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (to.meta.skipAuth || to.path === '/login') {
      next()
    } else {
      next({path: '/login', query: {redirect: to.redirect}})
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
